package com.htc.config;

import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * ES配置
 *
 * @author: htc
 * @date: Created in 11:26 2018/5/30.
 */
@Configuration
public class ElasticSearchConfig {

    @Value("${elasticsearch.host}")
    private String esHost;

    @Value("${elasticsearch.tcp.port}")
    private int esTcpPort;

    @Value("${elasticsearch.cluster.name}")
    private String esName;

    @Bean
    public TransportClient esClient() throws UnknownHostException {
        //初始化配置
        Settings settings = Settings.builder()
                .put("cluster.name", this.esName)
                //自动发现节点
                .put("client.transport.sniff", true)
                .build();

        //初始化master节点
        InetSocketTransportAddress master = new InetSocketTransportAddress(
                InetAddress.getByName(esHost),
                esTcpPort
        );

        TransportClient client = new PreBuiltTransportClient(settings);
        //将节点加入集群
        client.addTransportAddress(master);
        return client;


//        //ES节点地址
//        InetSocketTransportAddress node = new InetSocketTransportAddress(
//                InetAddress.getByName("localhost"),
//                //这里是ES的TCP端口，而不是ES的HTTP端口
//                9300
//        );
//
//        //ES配置
//        Settings settings = Settings.builder()
//                .put("cluster.name", "htc")
//                .build();
//        TransportClient client = new PreBuiltTransportClient(settings);
//        //添加节点地址，如果是集群，可以addTransportAddress()多次执行
//        client.addTransportAddress(node);
//        return client;
    }
}
